<?php
/**
 * Created By Project
 * Author: 陈东
 * Copyright：陈东
 * Source Code：陈东
 * Explain：I shall not authorize for any other commercial purposes, law breakers must be prosecuted.
 */
function getURL(){
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = $protocol.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
	$url = str_replace(':80', '', $url);
	$url = explode('#', $url)[0];
	return $url;
}
/**
 * 根据字符串获取域名
 */
function get_domain($url) {
	$pattern = "/[w-] .(com|net|org|gov|cc|biz|info|cn)(.(cn|hk))*/";
	preg_match ( $pattern, $url, $matches );
	if (count ( $matches ) > 0) {
		return $matches [0];
	} else {
		$rs = parse_url ( $url );
		$main_url = $rs ["host"];
		if (! strcmp ( long2ip ( sprintf ( "%u", ip2long ( $main_url ) ) ), $main_url )) {
			return $main_url;
		} else {
			$arr = explode ( ".", $main_url );
			$count = count ( $arr );
			$endArr = array (
					"com",
					"net",
					"org",
					"3322"
			);
			if (in_array ( $arr [$count - 2], $endArr )) {
				$domain = $arr [$count - 3] . "." . $arr [$count - 2] . "." . $arr [$count - 1];
			} else {
				$domain = $arr [$count - 2] . "." . $arr [$count - 1];
			}
			return $domain;
		}
	}
}

/**
 * 提取网址字符串中的参数
 */
function getLetvArray($url,$key){
	$p = [];
	try {
		$params = explode("?", $url);
		$arrayParams = explode("&", $params[1]);
		foreach ($arrayParams as $item) {
			$params1 = explode("=", $item);
			$p[$params1[0]] = $params1[1];
		}
	} catch(Exception $e){

	}
	if(is_array($p)){
		return $p[$key];
	}
}
/**
 * 设置分页样式
 * $obj 传入分页对象
 */
function pagestyle($obj=null){
	if(isset($obj)){
		$Page = $obj;
		$Page->lastSuffix=false;
		$Page->setConfig('header','&nbsp;&nbsp;[共<b>%TOTAL_ROW%</b>条记录&nbsp;&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页]');
		$Page->setConfig('prev','上一页');
		$Page->setConfig('next','下一页');
		$Page->setConfig('last','末页');
		$Page->setConfig('first','首页');
		$Page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
		return $Page;
	}
}
/**
 * 生成随机防伪码
 */
function generate_fwei( $length = 15 ) {
	// 密码字符集，可任意添加你需要的字符
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$password = '';
	for ( $i = 0; $i < $length; $i++ ){
		// 这里提供两种字符获取方式
		// 第一种是使用 substr 截取$chars中的任意一位字符；
		// 第二种是取字符数组 $chars 的任意元素
		// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
	}
	return $password;
}

/**
 * 判断是否是PC还是移动端
 */
function ismobile() {
	// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
	if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
		return true;

	//此条摘自TPM智能切换模板引擎，适合TPM开发
	if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
		return true;
	//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
	if (isset ($_SERVER['HTTP_VIA']))
		//找不到为flase,否则为true
		return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
	//判断手机发送的客户端标志,兼容性有待提高
	if (isset ($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array(
				'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
		);
		//从HTTP_USER_AGENT中查找手机浏览器的关键字
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	//协议法，因为有可能不准确，放到最后判断
	if (isset ($_SERVER['HTTP_ACCEPT'])) {
		// 如果只支持wml并且不支持html那一定是移动设备
		// 如果支持wml和html但是wml在html之前则是移动设备
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}

/**
 * 字符串截取
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
	if(function_exists("mb_substr")){
		$slice= mb_substr($str, $start, $length, $charset);
	}elseif(function_exists('iconv_substr')) {
		$slice= iconv_substr($str,$start,$length,$charset);
	}else{
		$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
		$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
		$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
		$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
	}
	$fix='';
	if(strlen($slice) < strlen($str)){
		$fix='...';
	}
	return $suffix ? $slice.$fix : $slice;
}

/**
 * 字符串截取1
 */
function msubstr1($str, $start=0, $length, $charset="utf-8", $suffix=true){
	if(function_exists("mb_substr")){
		$slice= mb_substr($str, $start, $length, $charset);
	}elseif(function_exists('iconv_substr')) {
		$slice= iconv_substr($str,$start,$length,$charset);
	}else{
		$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
		$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
		$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
		$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
		preg_match_all($re[$charset], $str, $match);
		$slice = join("",array_slice($match[0], $start, $length));
	}
	$fix='';
	return $suffix ? $slice.$fix : $slice;
}

/**
 * curl get方式
 */
function request_get($url){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	$output = curl_exec($ch);
	curl_close($ch);
	return json_decode($output,true);
	//return $output;
}

/**
 * curl post方式
 */
function request_post1($url,$post_data){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// post数据
	curl_setopt($ch, CURLOPT_POST, 1);
	// post的变量
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	$output = curl_exec($ch);
	curl_close($ch);
	//返回获得的数据
	return json_decode($output,true);
}

/**
 * curl post get方式
 */
function http($url, $data='', $method='GET'){
	$curl = curl_init(); // 启动一个CURL会话
	curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
	curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
	curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
	curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
	if($method=='POST'){
		curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
		if ($data != ''){
			curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
		}
	}
	curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
	curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
	$tmpInfo = curl_exec($curl); // 执行操作
	curl_close($curl); // 关闭CURL会话
	//return $tmpInfo; // 返回数据
	return json_decode($tmpInfo,true);
}

/**
 * get参数拼接
 */
function parameter_joint_get($pararray= null){
	if(empty($pararray) && !is_array($pararray)) return false;
	$res_str = null;
	foreach($pararray as $key=>$val){
		$res_str .= $key.'='.$val.'&';
	}
	$res_str = '?'.rtrim($res_str,'&');
	return $res_str;
}

/*根据IP获取地区*/
function iptoarea(){
	$url = "http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip();
	$r = request_get($url);
	return $r['data'];
}
/**
 * 显示分页limit返回值
 */
function limitbakstr($obj=null){
	if(isset($obj)){
		return $obj->firstRow.','.$obj->listRows;
	}
}
/**
 * 判断是否微信登陆
 */
function islogin($getURL){
	if(empty($_COOKIE['user_userinfo'])){
		header("Location:".C('LOGINADDRES').$getURL);
		exit;
	}else{
		return true;
	}
}

/**
 * 根据DOMAINID获取商品信息
 */
function get_shopinfo($domain = null){
	$shopreult = json_decode(file_get_contents("http://api.hrtv.cn/newproduct/GetproductInfosByDomainId?domainId=".$domain));
	$shoparray = array();
	foreach ($shopreult as $shop){
		if(is_array($shop)){
			$shoparray[] = $shop;
		}
	}
	if(!empty($shoparray[0])){
		$shoplist = $shoparray[0];
	}else{
		$shoparray = array();
		foreach ($shopreult as $v){
			$shoparray[] = $v;
		}
		$shoparray1 = array();
		foreach ($shoparray[1] as $shop){
			$shoparray1[] = $shop;
		}
		$shoplist = $shoparray1;
	}
	return $shoplist;
}
?>